﻿
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Report.WebApi.Entities;
using Report.WebApi.Extensions;
using Report.WebApi.Models;
using Report.WebApi.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DataWasher.WebApi.Repositories
{
    public class SysDomainRepository : RepositoryBase<SysDomain>, ISysDomainRepository
    {
        private readonly DBContext _context;
        public SysDomainRepository(DBContext context) : base(context)
        {
            _context = context;
        }

        public async Task<List<DomainModel>> GetDomainList(string domainId, string funcName, int level = -1)
        {
            var domainList = new List<DomainModel>();

            var domains = await GetOriginDomains(domainId, funcName);
            if (level != -1)
                domains = domains.Where(x => x.tLevel == level).ToList();
            domains.ForEach(x =>
           {
               domainList.Add(new DomainModel()
               {
                   DomainId = x.DomainId.ToString().ToLower(),
                   DomainName = x.DomainName,
                   ParentDomainId = x.ParentDomainId.ToString().ToLower(),
                   DomainIds = new List<string>(),
                   Level = x.tLevel,
                   DomainTag = x.DomainTag
               });

           });
            if (level == -1)
                return domainList;
            var originDomains = new List<SysDomainEntity>();
            domainList.ForEach(async x =>
            {
                originDomains = await GetOriginDomains(x.DomainId, funcName);
                x.DomainIds = originDomains.Select(x => x.ParentDomainId.ToString().ToLower()).ToList();

            });
            // (await GetOriginDomains(x.DomainId.ToString())).ToList().Select(x => x.DomainId.ToString().ToLower()).ToList()
            return domainList;
        }

        public async Task<List<SysDomainEntity>> GetOriginDomains(string domainId, string funcName)
        {
            var parameters = new List<SqlParameter>();
            var domains = _context.Database.SqlQuery<SysDomainEntity>($"select * from {funcName}('{domainId.ToUpper()}')", parameters.ToArray());
            return domains;
        }
    }
}
